package com.hqyj.realm;

import com.alibaba.fastjson.JSONObject;
import com.hqyj.pojo.User;
import com.hqyj.service.IUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.HashSet;
import java.util.Objects;
import java.util.Set;

public class UserRealm extends AuthorizingRealm {

    @Autowired
    private IUserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取用户信息
//        JSONObject userJson = JSONObject.parseObject(principalCollection.toString());
//
//        Integer id = userJson.getInteger("uid");
//        //查询数据库，根据用户id获取用户角色，权限等信息
//        UserRole userRole = userService.getUserRoleByUserId(id);
//
//        //获取到userRole对象后，把roleName传给shiro的SimpleAuthorizationInfo对象
//        Set<String> roleSet = new HashSet<>();
//        if (!Objects.isNull(userRole)) {
//            roleSet.add(userRole.getRoleName());
//        }
//
//        //获取权限集合
//        Set<String> permSet = new HashSet<>();
//
//        //把roleset添加到SimpleAuthorizationInfo对象中
//        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
//        authorizationInfo.addRoles(roleSet);
//
//        //把用户权限集合添加到SimpleAuthorizationInfo对象中
//        authorizationInfo.setStringPermissions(permSet);
//        return authorizationInfo;
        return null;
    }

    /**
     * 认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;

        User user = userService.getUserInfoByName(token.getUsername(), String.valueOf(token.getPassword()));

        if (Objects.isNull(user)) {
            throw new UnknownAccountException();
        }
        //把用户信息存入redis中
        String userkey = "user:"+user.getUserEmail();
        redisTemplate.opsForValue().set(userkey,user);
        //把user信息存入服务端的session内
        SecurityUtils.getSubject().getSession().setAttribute("userkey",user);
        return new SimpleAuthenticationInfo(user,token.getPassword(),"");
    }


}
